package com.yetong.domain.strategy.service.armory;

import com.yetong.domain.strategy.model.entity.StrategyAwardEntity;
import com.yetong.domain.strategy.model.entity.StrategyEntity;
import com.yetong.domain.strategy.model.entity.StrategyRuleEntity;
import com.yetong.domain.strategy.repository.IStrategyRepository;
import com.yetong.types.common.Constants;
import com.yetong.types.enums.ResponseCode;
import com.yetong.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.util.*;

/**
 * 作者：叶童
 * 时间：2025/5/1
 * 策略装配库，负责初始化策略计算
 */
@Service
@Slf4j
public class StrategyArmoryDispatch implements IStrategyArmory,IStrategyDispatch{
    @Resource
    private IStrategyRepository repository;
    private final SecureRandom secureRandom = new SecureRandom();

    @Override
    public boolean assembleLotteryStrategy(Long strategyId) {
        //1.查询策略配置
        List<StrategyAwardEntity> strategyAwardEntities = repository.queryStrategyAwardList(strategyId);

        //缓存奖品库存，用于decr扣减库存使用
        for (StrategyAwardEntity strategyAwardEntity : strategyAwardEntities) {
            Integer awardId = strategyAwardEntity.getAwardId();
            Integer awardCount = strategyAwardEntity.getAwardCount();
            cacheStrategyAwardCount(strategyId,awardId,awardCount);
        }

        //3.1默认装配
        assembleLotteryStrategy(String.valueOf(strategyId), strategyAwardEntities);

        //2.权重规则配置-适用于rule_weight权重规则配置
        StrategyEntity strategyEntity=repository.queryStrategyEntityByStrategyId(strategyId);
        String ruleWeight = strategyEntity.getRuleWeight();
        if(ruleWeight==null){
            return true;
        }
        StrategyRuleEntity strategyRuleEntity=repository.queryStrategyRule(strategyId,ruleWeight);
        if(strategyRuleEntity==null){
            throw new AppException(ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getCode(),ResponseCode.STRATEGY_RULE_WEIGHT_IS_NULL.getInfo());

        }
        Map<String, List<Integer>> ruleWeightValueMap = strategyRuleEntity.getRuleWeightValues();
        for (String key : ruleWeightValueMap.keySet()) {
            List<Integer> ruleWeightValues = ruleWeightValueMap.get(key);
            ArrayList<StrategyAwardEntity> strategyAwardEntitiesClone = new ArrayList<>(strategyAwardEntities);
            strategyAwardEntitiesClone.removeIf(entity -> !ruleWeightValues.contains(entity.getAwardId()));
            assembleLotteryStrategy(String.valueOf(strategyId).concat(Constants.UNDERLINE).concat(key), strategyAwardEntitiesClone);
        }

        return true;


    }

    private void assembleLotteryStrategy(String key,List<StrategyAwardEntity> strategyAwardEntities){
        //1.获取最小概率值
        BigDecimal minAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .min(BigDecimal::compareTo)
                .orElse(BigDecimal.ZERO);
        //2.获取概率总和
        BigDecimal totalAwardRate = strategyAwardEntities.stream()
                .map(StrategyAwardEntity::getAwardRate)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        //3.获取概率范围 1 / 0.01
        BigDecimal rateRange = totalAwardRate.divide(minAwardRate, 0, RoundingMode.CEILING);//向上取整
        //4.生成策略奖品概率查找表,这里指在List集合中，存放对应的奖品占位即可，占位越多等于概率越高
        List<Integer> strategyAwardSearchRateTables=new ArrayList<>(rateRange.intValue());
        for (StrategyAwardEntity strategyAward : strategyAwardEntities) {
            Integer awardId = strategyAward.getAwardId();
            BigDecimal awardRate = strategyAward.getAwardRate();
            //计算出每个概率值存放到表数量，循环填充
            for (int i = 0; i < rateRange.multiply(awardRate).setScale(0, RoundingMode.CEILING).intValue(); i++) {
                strategyAwardSearchRateTables.add(awardId);
            }
        }
        //5.对存储的奖品进行乱序，循环填充
        Collections.shuffle(strategyAwardSearchRateTables);
        //6.生产Map集合，key值对应的就是后续的概率值，通过概率获得对应的奖品ID
        Map<Integer,Integer> shuffledStrategyAwardSearchRateTables=new HashMap<>();
        for (int i = 0; i < strategyAwardSearchRateTables.size(); i++) {
            shuffledStrategyAwardSearchRateTables.put(i, strategyAwardSearchRateTables.get(i));
        }
        //7.存储到redis
        repository.storeStrategyAwardSearchRateTables(key,shuffledStrategyAwardSearchRateTables.size(),shuffledStrategyAwardSearchRateTables);


    }

    @Override
    public Integer getRandomAwardId(Long strategyId) {
        //分布式部署下，不一定为当前应用的策略装配，也就是值不一定保存到本应用，而是分布式应用，所以需要从Redis中获取
        int rateRange = repository.getRateRange(strategyId);
        //通过生成的随机值，进行抽奖，获取到概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(String.valueOf(strategyId),new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Integer getRandomAwardId(Long strategyId, String ruleWeightValue) {

        String key=String.valueOf(strategyId).concat("_").concat(ruleWeightValue);
        //分布式部署下，不一定为当前应用的策略装配，也就是值不一定保存到本应用，而是分布式应用，所以需要从Redis中获取
        int rateRange = repository.getRateRange(key);
        //通过生成的随机值，进行抽奖，获取到概率值奖品查找表的结果
        return repository.getStrategyAwardAssemble(key,new SecureRandom().nextInt(rateRange));
    }

    @Override
    public Boolean subtractionAwardStock(Long strategyId, Integer awardId) {
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        //库存扣减

        return repository.subtractionAwardStock(cacheKey);
    }

    private void cacheStrategyAwardCount(Long strategyId, Integer awardId, Integer awardCount) {
        //缓存奖品库存
        String cacheKey = Constants.RedisKey.STRATEGY_AWARD_COUNT_KEY + strategyId + Constants.UNDERLINE + awardId;
        repository.cacheStrategyAwardCount(cacheKey, awardCount);


    }

}
